package com.example.zzx.dovebook.booksearch.searchresult

import com.example.baselibrary.LoadCallback
import com.example.baselibrary.net.HttpUtil
import com.example.zzx.dovebook.base.BaseLiveData
import com.example.zzx.dovebook.base.BaseViewModel
import com.example.zzx.dovebook.base.ValueWrapper.*
import com.example.zzx.dovebook.base.model.BookShare

class SearchResultViewModel(repository: SearchResultRepository): BaseViewModel<SearchResultRepository>(repository) {

    private val searchBookShareKeys = arrayOf(
        "userId",
        "keyword",
        "startPosition"
    )

    fun searchBookShare(fragment: SearchResultFragment, userId: String, keyword: String, startPosition: Int): BaseLiveData<List<BookShareSearch>> {
        val result = BaseLiveData<List<BookShareSearch>>()
        val params = HttpUtil.wrapParams(searchBookShareKeys, userId, keyword, startPosition)
        repository.searchBookShare(params, object: LoadCallback<List<BookShare>> {
            override fun loadSuccess(data: List<BookShare>) {
                result.postValue(mutableListOf<BookShareSearch>().apply {
                    for (bookShare in data) {
                        add(BookShareSearch(fragment, bookShare))
                    }
                }, TYPE_NORMAL)
            }

            override fun loadFailed(errorMessage: String?) {
                result.postValue(null, TYPE_FAILED)
            }

            override fun loadNull(message: String?) {
                result.postValue(null, TYPE_NO_CONTENT)
            }

        })
        return result
    }

}